﻿using System;
using System.IO;
using LockerRack.Exceptions;
using LockerRack.Interfaces;
using Microsoft.Practices.Unity;

namespace LockerRack.Drawers
{
    /// <summary>
    /// 
    /// </summary>
    public class DrawerFile : IDrawerFile
    {
        public IDrawerFileStuff Contents { get; private set; }

        public DrawerFile(IUnityContainer resolver)
            : this(string.Empty, resolver)
        {
            
        }

        public DrawerFile(string file, IUnityContainer resolver)
        {
            Name = Path.GetFileName(file);
            Filename = file;
            Resolver = resolver;
        }

        public string Name { get; set; }
        public string Filename { get; set; }
        public IUnityContainer Resolver { get; set; }

        public bool SaveContent(string folder, out LockerException lex)
        {
            if(Contents == null)
            {
                lex = new LockerException("Draver file container is empty, can't save file");
                return false;
            }

            return Contents.Save(folder, out lex);
        }

        public bool LoadContent(string folder, out LockerException lex)
        {
            try
            {
                var drawerFileResolver = Resolver.Resolve<IDrawerFileResolver>();
                Contents = drawerFileResolver.LoadContentObject(this);
                return Contents.Load(Filename, out lex);
            }
            catch (Exception ex)
            {
                lex = new LockerException("Load file content error!", ex);
            }

            return false;
        }

        public bool CreateNewContent(IDrawerFileStuff content, out LockerException lex)
        {
            lex = null;
            Contents = content;

            return true;
        }

        public void Dispose()
        {
            Contents.Dispose();
        }
    }
}
